package com.teng.mylibrary.net

import android.content.Context
import com.alibaba.fastjson.JSONObject
import com.google.gson.Gson
import com.teng.mylibrary.util.SPUtil
import okhttp3.Cache
import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit

/**
 * KotlinFrame
 * Created by Dan on 2019-05-28
 * RetrofitHelper
 * Version 1.0
 * CopyRight Mycard
 */
object RetrofitHelper {

    private const val HTTP_RESPONSE_DISK_CACHE_MAX_SIZE = 10 * 1024 * 1024;//缓存最大大小;


    //用来保存retrofit创建的接口API，防止每次都create而耗费内存
    private val apiMap: HashMap<String, Any> = hashMapOf()

    @Volatile
    private lateinit var retrofit: Retrofit

    @Suppress("UNCHECKED_CAST")
    fun <T> create(clazz: Class<T>): T {
        if (!apiMap.contains(clazz.name)) {
            apiMap[clazz.name] = retrofit.create(clazz) as Any
        }
        return apiMap[clazz.name] as T
    }


    fun init(context: Context, baseUrl: String) {
        synchronized(Retrofit::class.java) {
            retrofit = Retrofit.Builder()
                //服务器地址
                .baseUrl(baseUrl)
                //设置OKHttpClient
                .client(getOkHttpClient(context))
                //String转换器，防止提交的参数带引号
                .addConverterFactory(ScalarsConverterFactory.create())
                //Gson转化器
                .addConverterFactory(GsonConverterFactory.create())
                //RxJava
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()

            apiMap.clear()
        }
    }

    private fun getOkHttpClient(context: Context): OkHttpClient {
        //日志拦截器
        val loggingInterceptor = HttpLoggingInterceptor();
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY

        //设置缓存
        val cacheDir = File(context.cacheDir, "HttpCache")
        val cache = Cache(cacheDir, HTTP_RESPONSE_DISK_CACHE_MAX_SIZE.toLong())

        return OkHttpClient.Builder()
            //打印日志
            .addInterceptor(loggingInterceptor)
            //设置Cache目录
            .cache(cache)
            //失败重连
            .retryOnConnectionFailure(true)
            //timeout
            .connectTimeout(SPUtil.getConnectTimeOut().toLong(), TimeUnit.SECONDS)
            .readTimeout(SPUtil.getConnectTimeOut().toLong(), TimeUnit.SECONDS)
            .writeTimeout(SPUtil.getConnectTimeOut().toLong(), TimeUnit.SECONDS)
            .build()
    }

    fun getRequestBody(body: JSONObject?): RequestBody {
        val appInfo = JSONObject()
        appInfo["Body"] = body
        return RequestBody.create(
            MediaType.parse("application/json; charset=utf-8"),
            Gson().toJson(appInfo)
        )
    }

}